package com.kmist.xiakexing.presenters;

import android.util.Log;

import com.kmist.xiakexing.interfaces.ITaskCallback;
import com.kmist.xiakexing.interfaces.ITaskPresenter;
import com.kmist.xiakexing.main.socket.DataRecver;
import com.kmist.xiakexing.main.socket.DataSender;
import com.kmist.xiakexing.main.socket.ISocketCallback;
import com.kmist.xiakexing.main.socket.SockPresenter;
import com.kmist.xiakexing.main.socket.cmd;
import com.kmist.xiakexing.main.socket.retCode;
import com.kmist.xiakexing.tools.Config;
import com.kmist.xiakexing.utils.scene.PlayerBean;
import com.kmist.xiakexing.utils.scene.PlayerTaskBean;
import com.kmist.xiakexing.utils.scene.TaskBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TaskPresenter implements ITaskPresenter, ISocketCallback {

    private static final String TAG = "TASK";
    private static TaskPresenter sInstance = null;
    private static PlayerPresenter playerPresenter;
    private final SockPresenter sockPresenter;
    private ITaskCallback callback;
    private TaskBean curTask;
    private PlayerTaskBean curPlayerTask;
    private PlayerBean player;

    private boolean isTaskLoadedTag = false;


    public TaskPresenter(){
        sockPresenter = SockPresenter.getInstance();
        playerPresenter = PlayerPresenter.getInstance();
        sockPresenter.setCallback(this);
        curTask = new TaskBean();
    }

    public static TaskPresenter getInstance(){
        if(sInstance == null){
            synchronized (TaskPresenter.class){
                sInstance = new TaskPresenter();
            }
        }
        return sInstance;
    }

    @Override
    public void addTask(PlayerBean player, TaskBean task) {
        //TODO
    }

    @Override
    public void delTask(PlayerBean player, TaskBean task) {
        //TODO
    }

    @Override
    public void getTask(String taskid) {

        try {
            if(taskid != ""){
                JSONObject jsonObject = Config.val2json("taskid", taskid);
                DataSender info = new DataSender(cmd.CMD_TASK_GETTASK, jsonObject.toString());
                sockPresenter.sendMessage(info.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getTask(TaskBean task) {
        curTask = task;
        try {
            if(task.getTaskId() != 0){
                JSONObject jsonObject = Config.val2json("taskid", task.getTaskId()+"");
                DataSender info = new DataSender(cmd.CMD_TASK_GETTASK, jsonObject.toString());
                sockPresenter.sendMessage(info.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getPlayerAllTask(String sid) {
        //TODO
    }

    @Override
    public PlayerTaskBean getPlayerTask(String sid, int taskid) {

        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sid", sid);
            jsonObject.put("taskid", taskid);
            DataSender info = new DataSender(cmd.CMD_TASK_GETPLAYERTASKONCE, jsonObject.toString());
            sockPresenter.sendMessage(info.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        while(!isTaskLoadedTag){
            Log.d(TAG, "wait task");
        }
        isTaskLoadedTag = false;
        return curPlayerTask;
    }

    @Override
    public String getTaskTypeStr(int taskType) {
        return "";
    }

    /**
     * 根据当前任务的不同状态， 获取任务的对白
     * @param taskStatus 任务状态
     * @param taskinfo 当前任务的对白数组
     * @return 任务对白
     */
    @Override
    public String getTaskDialogue(int taskStatus, String taskinfo) {
        String out = "";
        try {
            JSONArray iArray = new JSONArray(taskinfo);

            if(taskStatus == 0)
            {
                out = iArray.getString(0);
            }else if(taskStatus == 3){
                out = iArray.getString(2);
            }else{
                out = iArray.getString(1);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return out;
    }

    /**
     * 获取当前任务的状态
     *
     * @param task @return
     * @param nid
     */
    @Override
    public String getTaskStatusStr(TaskBean task, int nid) {
        String out = "";
        String TaskTypeStr = "";
        String TaskStatusStr = "";

        player = playerPresenter.getPlayerd();
        PlayerTaskBean curPlayerTask = getPlayerTask(player.getSid(), task.getTaskId());

        if(task.getTaskLeixing() == 1 || task.getTaskLeixing() == 2){
            TaskTypeStr = (task.getTaskLeixing() == 1 )? " [普通]":" [日常]";
            if(curPlayerTask == null){
                if(task.getTaskType() != 3){
                    TaskStatusStr = " [?]";
                }else if(task.getTaskRequest() == nid){
                    TaskStatusStr = " [?]";
                }
            }else{
                if(curPlayerTask.getTaskStatus() == 2){
                    if (curPlayerTask.getTaskType() != 3){
                        TaskStatusStr = " [!]";
                    }else if(curPlayerTask.getTaskCount() == nid){
                        TaskStatusStr = " [!]";
                    }
                }
            }

        }

        if(task.getTaskLeixing() == 3){
            if(curPlayerTask != null){
                if(curPlayerTask.getTaskStatus() == 2){
                    if(curPlayerTask.getTaskType() != 3){
                        TaskTypeStr = " [主线]";
                        TaskStatusStr = " [!]";
                    }else if(curPlayerTask.getTaskCount() == nid){
                        TaskTypeStr = " [主线]";
                        TaskStatusStr = " [!]";
                    }
                }
            }else{
                PlayerTaskBean lastTask = getPlayerTask(player.getSid(), task.getTaskLastTaskID());
                if(lastTask != null){
                    if(lastTask.getTaskStatus() == 3){
                        if(task.getTaskType() != 3){
                            TaskTypeStr = " [主线]";
                            TaskStatusStr = " [?]";
                        }else if(task.getTaskRequest() == nid){
                            TaskTypeStr = " [主线]";
                            TaskStatusStr = " [?]";
                        }
                    }
                }
            }
        }


        out = TaskTypeStr + TaskStatusStr;
        return out;
    }

    @Override
    public void acceptTask(String sid, int taskId) {
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sid", sid);
            jsonObject.put("taskid", taskId);
            DataSender info = new DataSender(cmd.CMD_TASK_ADDPLAYERTASK, jsonObject.toString());
            sockPresenter.sendMessage(info.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateTaskStatus(String sid, int taskid, int status) {
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sid", sid);
            jsonObject.put("taskid", taskid);
            jsonObject.put("taskStatus", status);
            DataSender info = new DataSender(cmd.CMD_TASK_UPDATETASKSTATUS, jsonObject.toString());
            sockPresenter.sendMessage(info.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void taskStatusOver(String sid, int taskid) {
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sid", sid);
            jsonObject.put("taskid", taskid);
            DataSender info = new DataSender(cmd.CMD_TASK_PLAYERTASKOVER, jsonObject.toString());
            sockPresenter.sendMessage(info.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void registerViewCallback(ITaskCallback callback) {
        this.callback = callback;
    }

    @Override
    public void unRegisterViewCallback(ITaskCallback callback) {
        this.callback = null;
    }

    @Override
    public void onConnected() {
        //sock notodo
    }

    @Override
    public void onNetworkError() {
        //notodo sock
    }

    @Override
    public void onDataRecved(DataRecver dataRecver) {

        if (!dataRecver.getResp_cmd().substring(0,2).equals(cmd.CMD_TASK)) {
            return;
        }

        switch (dataRecver.getResp_code()){

            case retCode.RET_OK:{
                if(dataRecver.getResp_cmd().equals(cmd.CMD_TASK_GETTASK)){
                    getTask_handler(dataRecver);
                }else if(dataRecver.getResp_cmd().equals(cmd.CMD_TASK_GETPLAYERTASKONCE)){
                    getPlayerTaskOnce_handler(dataRecver);
                }else{
                    Log.d("RECV:"," 操作成功！");
                }
            } break;
            case retCode.RET_NONE: /* do nothing ,but success */
                curPlayerTask = null;
                isTaskLoadedTag = true;
                break;
            default:
                Log.d("RECV:","cmd exe ERROR: "+dataRecver.getResp_code());
                break;
        }
    }

    private void getPlayerTaskOnce_handler(DataRecver dataRecver) {
        if(parseTaskInfo2(dataRecver.getResp_data())){
            callback.onTaskLoaded(curTask);
        }else{
            callback.onTaskLoadError();
        }
        isTaskLoadedTag = true;
    }

    private boolean parseTaskInfo2(String resp_data) {
        try{
            JSONObject root = new JSONObject(resp_data);
            JSONObject task = root.getJSONObject("task");
            if(curPlayerTask!=null){
                curPlayerTask = null;
            }
            curPlayerTask = new PlayerTaskBean();
            curPlayerTask.setTaskId(task.getInt("id"));
            curPlayerTask.setTaskName(task.getString("name"));
            curPlayerTask.setTaskType(task.getInt("type")); //对话、打怪、收集
            curPlayerTask.setTaskRequest(task.getInt("request"));
            curPlayerTask.setTaskItem(task.getString("item"));
            curPlayerTask.setTaskEquipment(task.getInt("equipment"));
            curPlayerTask.setTaskExp(task.getInt("exp"));
            curPlayerTask.setTaskYxb(task.getInt("yxb"));
            curPlayerTask.setTaskCount(task.getInt("count"));
            curPlayerTask.setTaskYaopin(task.getString("yaopin"));
            curPlayerTask.setTaskSkill(task.getString("skill"));
            curPlayerTask.setTaskNowCount(task.getInt("nowCount"));
            curPlayerTask.setTaskStatus(task.getInt("status"));

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void getTask_handler(DataRecver dataRecver) {
        if(parseTaskInfo(dataRecver.getResp_data())){
            callback.onTaskLoaded(curTask);
        }else{
            callback.onTaskLoadError();
        }
    }

    private boolean parseTaskInfo(String resp_data) {

        try{
            JSONObject root = new JSONObject(resp_data);
            JSONObject task = root.getJSONObject("task");

            curTask.setTaskId(task.getInt("id"));
            curTask.setTaskName(task.getString("name"));
            curTask.setTaskInfo(task.getString("info"));
            curTask.setTaskType(task.getInt("type")); //对话、打怪、收集
            curTask.setTaskRequest(task.getInt("request"));
            curTask.setTaskItem(task.getString("item"));
            curTask.setTaskEquipment(task.getInt("equipment"));
            curTask.setTaskExp(task.getInt("exp"));
            curTask.setTaskYxb(task.getInt("yxb"));
            curTask.setTaskCount(task.getInt("count"));
            curTask.setTaskYaopin(task.getString("yaopin"));
            curTask.setTaskSkill(task.getString("skill"));
            curTask.setTaskLastTaskID(task.getInt("lastTaskId"));

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
